package com.atguigu.juc.base;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncVSLockDemo {
    private final Lock lock = new ReentrantLock();

    public synchronized void m1() {

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t" + "come in------>");
    }

    public void m2() {
        try {
            if (lock.tryLock(3,TimeUnit.SECONDS)) {
                try {    System.out.println(Thread.currentThread().getName() + "\t" + "come in------>");
                    try {
                        TimeUnit.SECONDS.sleep(4);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }finally {
                    lock.unlock();
                }
            }else {
                System.out.println(Thread.currentThread().getName() + "\t"+"抢锁失败，请重试...");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();
        new Thread(() -> {
            syncVSLockDemo.m2();
        }, "t1").start();
        new Thread(() -> {
            syncVSLockDemo.m2();
        }, "t2").start();
    }
}
